package com.example.consumptionrecords.util.dashscope;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.fastjson.JSON;
import com.example.consumptionrecords.entity.dto.TextToImgDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 文生图
 * hhzr9
 * 2024 \ 03 \ 28
 */

@Component
public class DashScopeUtil {

	@Value("${ali.dash-scope.api-key}")
	private String API_KEY;

	/**
	 * @param textToImgDTO 文生图参数
	 * @throws ApiException      api异常
	 * @throws NoApiKeyException 没有apiKey异常
	 */
	public ImageSynthesisResult textToImg(TextToImgDTO textToImgDTO) throws ApiException, NoApiKeyException {
		// 设置调用的apiKey，正式使用时去掉注释
//		Constants.apiKey = API_KEY;
		ImageSynthesis is = new ImageSynthesis();
		ImageSynthesisParam param =
				ImageSynthesisParam.builder()
						.model(ImageSynthesis.Models.WANX_V1)
						.prompt(textToImgDTO.getPrompt())
						.negativePrompt(textToImgDTO.getNegativePrompt())
						.style(textToImgDTO.getStyle())
						.size(textToImgDTO.getSize())
						.n(textToImgDTO.getN())
						.seed(textToImgDTO.getSeed())
						.build();
		ImageSynthesisResult result = is.call(param);
		System.out.println(JSON.toJSONString(result));
		return result;
	}

	public ImageSynthesisListResult listTask() throws ApiException, NoApiKeyException {
		ImageSynthesis is = new ImageSynthesis();
		AsyncTaskListParam param = AsyncTaskListParam.builder().build();
		return is.list(param);
	}

	public ImageSynthesisResult fetchTask(String taskId) throws ApiException, NoApiKeyException {
		ImageSynthesis is = new ImageSynthesis();
		// If set DASHSCOPE_API_KEY environment variable, apiKey can null.
		return is.fetch(taskId, API_KEY);
	}
}
